package com.yqb.study.util;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yqb.study.modular.persistence.model.User;

/**
 * 用户bean对象和fast json相互转化
 */
public class FastJsonUtil {
	/**
	 * 将对象转换为json
	 * 
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj) {
		return JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteNullNumberAsZero);
	}

	/**
	 * 将json字符串转换为对象
	 * 
	 * @param jsonString
	 * @param clazz
	 * @return
	 */
	public static <T> T jsonToObject(String jsonString, Class<T> clazz) {
		return JSON.parseObject(jsonString, clazz);
	}

	/**
	 * 将字符串转换为List
	 * 
	 * @param jsonString
	 * @param clazz
	 * @return
	 */
	public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
		return JSON.parseArray(jsonString, clazz);
	}

	public static void main(String[] args) {
		User user = new User();
		user.setPhone("15006181953");
		user.setPassword("vinnie");
		String jsonStr = toJson(user);
		System.out.println("jsonStr : " + jsonStr);
		
		user = null;
		user = jsonToObject(jsonStr, User.class);
		
		List<User> userList = new ArrayList<User>();
		userList.add(user);
		userList.add(user);
		String jsonListStr = toJson(userList);
		System.out.println("jsonListStr : " + jsonListStr);
		userList = null;
		userList = jsonToList(jsonListStr, User.class);
	}
}
